import random
import redis
from connection import PhoenixConnect
from example import cities, coords


class GeoHashGenerator:
    conn = None  # phoenix connection
    rc: redis.StrictRedis = None  # redis client
    geo_key = ''

    def __init__(self, key, db_url, redis_url, redis_port=6379, redis_db=0):
        self.geo_key = key
        self.rc = redis.StrictRedis(host=redis_url, port=redis_port, db=redis_db)
        self.conn = PhoenixConnect(db_url)

    def start(self):
        select_cursor = self.conn.get_select_cursor()
        sql = 'select id, city from WELOG_SV.AV'

        select_cursor.execute(sql)

        av_list = select_cursor.fetchmany(100)
        count = len(av_list)
        total = count

        while count > 0:
            print(total)
            for i in range(0, count):
                # get id and city
                avid = av_list[i]['ID']
                city = av_list[i]['CITY']

                city_index = cities.index(city)

                cx = GeoHashGenerator.gen_random_coord(city_index)
                lon = cx[0]  # 经度
                lat = cx[1]  # 纬度

                self.rc.geoadd(self.geo_key, lon, lat, avid)

            av_list = select_cursor.fetchmany(100)
            count = len(av_list)
            total += count

        print('Done')

    @staticmethod
    def gen_random_coord(city_index):
        lon = '%d.%d' % (coords[city_index][0], random.randint(100000, 1000000))
        lat = '%d.%d' % (coords[city_index][1], random.randint(100000, 1000000))
        return [lon, lat]


if __name__ == '__main__':
    geo_key = 'near_av_geo'
    x = GeoHashGenerator(geo_key, db_url='http://xiaoma01:8765', redis_url='dev.xiaoma.com', redis_db=1)
    x.start()
    x.conn.conn.close()
    exit(0)
